#!/usr/bin/env python
# -*- coding:utf-8 -*-


import sys,argparse
import subprocess


sys.path.append("../")
from conf.config import mysqldb


REPORT_JAR='/home/etlctl/jar/report-excel-once-0.0.1.jar'

def command_parser():
    # 创建解析器
    parser = argparse.ArgumentParser(description=u"命令行参数解析")

    # 添加参数
    parser.add_argument("-c","--book_code", help=u"工作簿编码", type=str)
    parser.add_argument("-i","--book_id", help=u"工作簿id", type=str)
    parser.add_argument("-p", "--parameters", help=u"参数字典", type=str)

    return parser


def report_info(book_code):
    with mysqldb.cursor() as cursor:
        cursor.execute(
        'select id from etl_report_book where is_send=1 and book_code =%s',
        (book_code,))
        id_result=[str(item[0]) for item in cursor.fetchall()]
    return ','.join(id_result)

def start(bookid, params):
    command_str="java -jar %s -i %s -p '%s'"%(REPORT_JAR,bookid, params)
    print command_str
    child_process=subprocess.Popen(command_str, shell=True)
    (stdout,stderr)=child_process.communicate()
    child_process.wait()
    return child_process.returncode

if __name__ == '__main__':
    parser=command_parser()
    argv=parser.parse_args(sys.argv[1:])
    book_id = argv.book_id
    book_code = argv.book_code
    params = argv.parameters
    if book_code:
        book_id = report_info(book_code)
    if book_id != '':
        returncode=start(book_id,params)
        sys.exit(returncode)
